import axios from 'axios'
const service = axios.create({
  timeout: 60000, // request timeout
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers.accessToken = window.$CCDK.CCToken.getToken()
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const code = response.data.code || 200
    if (code !== 200) {
      return Promise.reject(response.data.msg == null ? '未知异常' : response.data.msg)
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)
const formateData = data => {
  return {
    head: {
      appType: 'cloudcc-plugin',
      appVersion: '1.0.0',
      accessToken: window.$CCDK.CCToken.getToken()
    },
    body: {
      ...data
    }
  }
}
export default {
  get: (url, data = {}, responseType = '') => {
    return service({
      url: url,
      method: 'get',
      params: data,
      responseType: responseType
    })
  },
  getLight: (url, data = {}, responseType = '') => {
    return service({
      url: url,
      method: 'get',
      params: data,
      responseType: responseType
    })
  },
  postLight: (url, data = {}) => {
    return service({
      url: url,
      method: 'post',
      data: { ...data }
    })
  },
  post: (url, data = {}, responseType = '') => {
    return service({
      url: url,
      method: 'post',
      data: formateData(data),
      responseType: responseType
    })
  },
  postParams: (url, data = {}) => {
    return service({
      url: url,
      method: 'post',
      params: data
    })
  },
  patch: (url, data = {}) => {
    return service({
      url: url,
      method: 'patch',
      data: formateData(data)
    })
  },
  delete: (url, data = {}) => {
    return service({
      url: url,
      method: 'delete',
      data: formateData(data)
    })
  },
  put: (url, data = {}) => {
    return service({
      url: url,
      method: 'put',
      data: formateData(data)
    })
  }
}
